package com.woniuxy.user.utils;

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class GaoDeMapUtil {
    private static final String GAO_DE_KEY = "11e0e70bfce48a737830e95670f14217";

    public static String getLonLat(String address) {
        try {
            String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + GAO_DE_KEY + "&address=" + address;
            String queryResult = getResponse(queryUrl);
            JSONObject job = JSONObject.parseObject(queryResult);
            JSONObject jobJSON = JSONObject.parseObject(job.getJSONArray("geocodes").get(0).toString());
            String LngAndLat = jobJSON.getString("location");
            return LngAndLat;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getResponse(String serverUrl) {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String address = "观音桥中信大厦";
        String lonLat = getLonLat(address);
        //分开输出精度和纬度
        System.out.println("经度：" + lonLat.split(",")[0]);
        System.out.println("纬度：" + lonLat.split(",")[1]);
    }
}